package com.hanxiaozhang.generatepdf;

import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import java.io.*;
import java.util.Date;


/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2025/6/9
 * @since 1.0.0
 */
public class BasicHtmlToPdf {

    public static void convertHtmlToPdf(String html, String outputPath) throws Exception {

        // 2. 指定中文字体路径(需要提前准备好字体文件)
        String fontPath = "springboot-some-function/src/main/java/com/hanxiaozhang/generatepdf/Alibaba-PuHuiTi-Light.ttf";
        try (OutputStream os = new FileOutputStream(outputPath)) {
            PdfRendererBuilder builder = new PdfRendererBuilder();

             // 设置纸张大小
            builder.useDefaultPageSize(210,297,BaseRendererBuilder.PageSizeUnits.MM);

            // 添加中文字体支持
            builder.useFont(new File(fontPath), "Alibaba");

            // 第二个参数是baseUrl，用于解析相对路径
            builder.withHtmlContent(html, null);
            builder.toStream(os);
            builder.run();
        }
    }

    public static void main(String[] args) {
        String html = "<html>"
                + "<head>"
                + "    <meta charset='UTF-8'/>"
                + "    <style>"
                + "        body { font-family: 'Alibaba'; }"
                + "        h1 { color: #0066cc; }"
                + "    </style>"
                + "</head>"
                +  "<body>"
                + "<h1>Hello PDF</h1>"
                + "<p>This is a test document generated by OpenHTMLToPDF</p>"
                + "<p>wrew 中文 werwe wer</p>"
                + "</body></html>";

        try {
            convertHtmlToPdf(html, "D://basic" +(new Date()).getTime()+".pdf" );
            System.out.println("PDF generated successfully!");
        } catch (Exception e) {
            System.err.println("Error generating PDF: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
